<template>
  <!--质保管理-合同页面-->
  <div>
    <el-form>
      <el-form-item>
        <el-button type="primary" @click="addContract()">新增</el-button>
      </el-form-item>
    </el-form>

    <el-dialog :title="dialogType === 'add'?'新增合同':'编辑合同'" :visible.sync="ContractVisible" :close-on-click-modal="false"
               :beforeClose="cancel">
      <el-form :model="contractDto" :rules="roleRules" ref="contractForm" label-width="100px">
        <el-form-item :label="dialogType === 'add'?'操作人':'当前操作人'" prop="operator">
          <el-input v-model="contractDto.operator" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="contractDto.contractNumber" :disabled="dialogType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="保修年限" prop="warrantyYear">
          <el-input-number v-model.number="contractDto.warrantyYear" :min="1" :step="1"  :disabled="dialogType === 'edit'"></el-input-number>
          <span>年</span>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="contractDto.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="contractDto.tel"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
    <custom-table
      :data="contractList"
      :columns="columns"
      :operationColumn="operationColumns"
      :pagination="pagination"
    >
    </custom-table>
  </div>
</template>
<script>
  import CustomTable from '@/components/table/CustomTable'
  import {getUserId, getName} from '@/utils/token'
  import {apiAddContract, apiGetContractList, apiUpdContract, apiDelContract} from '@/api/warranty/contract'
  import { validatePhone } from '@/utils/validation'

  export default {
    components: {
      CustomTable
    },
    created() {
      let listQuery = {
        pageSize: 10,
        pageNumber: 1
      }
      this.getContractList(listQuery)
    },
    data() {
      var checkDate = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请正确填入保修期限'))
        }
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数值'))
        } else {
          if (value < 1) {
            callback(new Error('必须大于1'))
          } else if (value > 127) {
            callback(new Error('数值太大了'))
          } else {
            callback()
          }
        }
      }
      return {
        columns: [
          {label: '操作人', name: 'operator', align: 'center'},
          {label: '合同编号', name: 'contractNumber', align: 'center'},
          {label: '保修年限', name: 'warrantyYear', align: 'center'},
          {label: '联系人', name: 'contact', align: 'center'},
          {label: '联系方式', name: 'tel', align: 'center'}
        ],
        contractList: [],
        contractDto: {
          operator: getName(),
          userId: getUserId(),
          contractNumber: '', // 合同编号
          warrantyYear: '', // 保修年限
          contact: '',
          tel: '',
          id: undefined
        },
        ContractVisible: false,
        operationColumns: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handelEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        roleRules: {
          contractNumber: [
            {required: true, message: '请填写合同编号', trigger: 'blur'},
            {max: 30, message: '长度不得超过30字符', trigger: 'blur'}],
          warrantyYear: [
            {required: true, validator: checkDate, trigger: 'blur'}],
          tel: [
            {validator: validatePhone, trigger: 'blur'}
          ],
          contact: [{max: 20, message: '长度不得超过20字符', trigger: 'blur'}]
        },
        dialogType: 'add',
        pagination: this.getData(this.getContractList)
      }
    },
    methods: {
      //弹出新增合同模态框
      addContract() {
        this.dialogType = 'add'
        this.ContractVisible = true
        if (this.$refs['contractForm']) {
          this.contractDto = {
            operator: getName(),
            userId: getUserId(),
            contractNumber: '', // 合同编号
            warrantyYear: '', // 保修年限
            contact: '',
            tel: '',
            id: undefined
          }
        }
        if (this.$refs['contractForm'] !== undefined) {
          this.$refs['contractForm'].resetFields()
        }
      },
      //弹出编辑合同模态框
      handelEdit(row) {
        this.contractDto.id = row.id
        this.contractDto.contractNumber = row.contractNumber
        this.contractDto.warrantyYear = row.warrantyYear
        this.contractDto.contact = row.contact
        this.contractDto.tel = row.tel
        this.dialogType = 'edit'
        this.ContractVisible = true
      },
      //提交
      submit() {
        this.$refs['contractForm'].validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      //新增合同
      addSubmit() {
        apiAddContract(this.contractDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.ContractVisible = false
          this.getContractList()
          this.$refs['contractForm'].resetFields()
        })
      },
      //获取合同List信息
      getContractList(listQuery) {
        apiGetContractList(listQuery).then(rsp => {
          this.contractList = rsp.data
          this.pagination.totalRecords = rsp.totalRecords
        }).catch(() => {
        })
      },
      //更新合同
      updSubmit() {
        apiUpdContract(this.contractDto).then(() => {
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          this.ContractVisible = false
          this.getContractList()
          this.$refs['contractForm'].resetFields()
        }).catch(() => {
        })
      },
      //删除合同
      handleDel(row) {
        this.$confirm('确定删除该合同?', '删除合同', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let listQuery = {
            id: row.id
          }
          apiDelContract(listQuery).then(rsp => {
            if (rsp.data !== undefined && rsp.data.status === 'error') {
              this.$message({
                showClose: true,
                type: 'error',
                message: rsp.data.message
              })
            } else if (rsp.resCode === '200') {
              this.$message({
                showClose: true,
                type: 'success',
                message: '删除成功!'
              })
            }
            this.getContractList()
          })
        }).catch(() => {
        })
      },
      //取消
      cancel() {
        this.ContractVisible = false
        this.$refs['contractForm'].resetFields()
      }
    }
  }
</script>
